package net.kevin.demo.hessian.module;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.caucho.hessian.client.HessianProxyFactory;

public class InterfaceServiceInterceptor implements MethodInterceptor, ApplicationContextAware, InitializingBean {

	@Autowired
	private InterfaceDependOnRegistry interfaceDependOnRegistry;
	private static Map<String, Object> proxyInterface = new HashMap<String, Object>();
	ApplicationContext act;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		act = applicationContext;
	}

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object[] arguments = invocation.getArguments();
		Method method = invocation.getMethod();
		
		Class<?> clazz = method.getDeclaringClass();
		Object hessionProxy = proxyInterface.get(clazz.getName());		
		return method.invoke(hessionProxy, arguments);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Set<Module> modules = interfaceDependOnRegistry.getModules();
		for (Module module : modules) {
			HessianProxyFactory factory = new HessianProxyFactory();
			String url = module.getEndpoint();
			for (String facade : module.getFacades()) {
				Class<?> clazz = act.getClassLoader().loadClass(facade);
				proxyInterface.put(facade, factory.create(clazz, url));
			}
		}
	}

}
